/*
VR钓鱼竿系统
支持VR控制器交互和物理模拟
专为Pico VR优化
*/

import * as THREE from 'three';
import { PicoVRConfig } from '../core/PicoVRConfig.js';

class FishingRod {
  constructor(scene, renderer) {
    this.scene = scene;
    this.renderer = renderer;
    
    // 钓鱼竿组件
    this.rodGroup = new THREE.Group();
    this.rodBody = null;
    this.fishingLine = null;
    this.bobber = null;
    this.hook = null;
    
    // 钓鱼状态
    this.isVRMode = false;
    this.isCasting = false;
    this.isReeling = false;
    this.lineLength = 5;
    this.maxLineLength = 20;
    this.minLineLength = 2;
    
    // VR控制器
    this.rightController = null;
    this.leftController = null;
    
    // 钓鱼位置
    this.bobberPosition = new THREE.Vector3(0, 0, -10);
    this.castTarget = new THREE.Vector3();
    
    // 动画参数
    this.castProgress = 0;
    this.reelProgress = 0;
    this.bobberFloating = 0;
    
    this.init();
  }
  
  init() {
    this.createFishingRod();
    this.createFishingLine();
    this.createBobber();
    this.setupVRControllers();
    this.scene.add(this.rodGroup);
  }
  
  createFishingRod() {
    // 钓鱼竿主体
    const rodGeometry = new THREE.CylinderGeometry(0.01, 0.02, 2, 8);
    const rodMaterial = new THREE.MeshPhongMaterial({
      color: 0x8B4513,
      shininess: 30
    });
    
    this.rodBody = new THREE.Mesh(rodGeometry, rodMaterial);
    this.rodBody.position.set(0, 1, 0);
    this.rodBody.rotation.x = -Math.PI / 6; // 斜向前方
    
    // 钓鱼竿握把
    const handleGeometry = new THREE.CylinderGeometry(0.03, 0.03, 0.3, 8);
    const handleMaterial = new THREE.MeshPhongMaterial({
      color: 0x2F4F4F
    });
    
    const handle = new THREE.Mesh(handleGeometry, handleMaterial);
    handle.position.set(0, -0.8, 0);
    
    this.rodBody.add(handle);
    this.rodGroup.add(this.rodBody);
  }
  
  createFishingLine() {
    // 创建钓鱼线
    const linePoints = [];
    for (let i = 0; i <= 50; i++) {
      linePoints.push(new THREE.Vector3(0, 0, -i * 0.2));
    }
    
    const lineGeometry = new THREE.BufferGeometry().setFromPoints(linePoints);
    const lineMaterial = new THREE.LineBasicMaterial({
      color: 0x333333,
      linewidth: 2
    });
    
    this.fishingLine = new THREE.Line(lineGeometry, lineMaterial);
    this.fishingLine.position.copy(this.getRodTipPosition());
    
    this.rodGroup.add(this.fishingLine);
  }
  
  createBobber() {
    // 创建浮漂
    const bobberGeometry = new THREE.SphereGeometry(0.05, 16, 16);
    const bobberMaterial = new THREE.MeshPhongMaterial({
      color: 0xFF4500,
      shininess: 100
    });
    
    this.bobber = new THREE.Mesh(bobberGeometry, bobberMaterial);
    this.bobber.position.copy(this.bobberPosition);
    
    // 创建鱼钩
    const hookGeometry = new THREE.ConeGeometry(0.01, 0.05, 8);
    const hookMaterial = new THREE.MeshPhongMaterial({
      color: 0x888888
    });
    
    this.hook = new THREE.Mesh(hookGeometry, hookMaterial);
    this.hook.position.set(0, -0.08, 0);
    this.hook.rotation.x = Math.PI;
    
    this.bobber.add(this.hook);
    this.scene.add(this.bobber);
  }
  
  setupVRControllers() {
    // 设置VR控制器
    this.rightController = this.renderer.xr.getController(0);
    this.leftController = this.renderer.xr.getController(1);
    
    // 右手控制器事件 - 主要钓鱼操作
    this.rightController.addEventListener('selectstart', (event) => {
      this.onTriggerPress(event, 'right');
    });
    
    this.rightController.addEventListener('selectend', (event) => {
      this.onTriggerRelease(event, 'right');
    });
    
    // 左手控制器事件 - 辅助操作
    this.leftController.addEventListener('selectstart', (event) => {
      this.onTriggerPress(event, 'left');
    });
    
    this.scene.add(this.rightController);
    this.scene.add(this.leftController);
  }
  
  onTriggerPress(event, hand) {
    if (hand === 'right') {
      if (!this.isCasting && !this.isReeling) {
        this.startCasting();
      } else if (this.isCasting) {
        this.releaseCast();
      }
    } else if (hand === 'left') {
      this.startReeling();
    }
    
    // 触觉反馈
    const controller = hand === 'right' ? this.rightController : this.leftController;
    PicoVRConfig.triggerFishingHaptic(controller, 'nibble');
  }
  
  onTriggerRelease(event, hand) {
    if (hand === 'left') {
      this.stopReeling();
    }
  }
  
  startCasting() {
    console.log('🎣 开始抛竿');
    this.isCasting = true;
    this.castProgress = 0;
    
    // 获取控制器位置作为抛竿目标
    if (this.rightController && this.rightController.position) {
      const controllerPos = this.rightController.position;
      this.castTarget.copy(controllerPos);
      this.castTarget.z -= 10; // 向前投掷
    }
  }
  
  releaseCast() {
    console.log('🌊 释放鱼线');
    this.isCasting = false;
    
    // 播放抛竿动画
    this.animateCast();
  }
  
  animateCast() {
    const duration = 1000; // 1秒动画
    const startTime = Date.now();
    
    const animate = () => {
      const elapsed = Date.now() - startTime;
      const progress = Math.min(elapsed / duration, 1);
      
      // 弧线轨迹
      const height = Math.sin(progress * Math.PI) * 3;
      const x = this.castTarget.x * progress;
      const z = this.castTarget.z * progress;
      
      this.bobberPosition.set(x, height, z);
      this.bobber.position.copy(this.bobberPosition);
      
      this.updateFishingLine();
      
      if (progress < 1) {
        requestAnimationFrame(animate);
      } else {
        // 抛竿完成，落水
        this.onBobberLanding();
      }
    };
    
    animate();
  }
  
  onBobberLanding() {
    console.log('💧 浮漂落水');
    
    // 触发水面涟漪（通过事件通知水面系统）
    this.dispatchEvent('bobberLanding', {
      position: this.bobberPosition.clone(),
      intensity: 1.5
    });
    
    // 触觉反馈
    PicoVRConfig.triggerFishingHaptic(this.rightController, 'splash');
  }
  
  startReeling() {
    if (this.lineLength > this.minLineLength) {
      console.log('🔄 开始收竿');
      this.isReeling = true;
    }
  }
  
  stopReeling() {
    console.log('⏸️ 停止收竿');
    this.isReeling = false;
  }
  
  // 模拟鱼咬钩
  simulateFishBite(intensity = 1) {
    console.log('🐟 鱼咬钩！');
    
    // 浮漂摇摆动画
    const duration = 2000;
    const startTime = Date.now();
    
    const animate = () => {
      const elapsed = Date.now() - startTime;
      const progress = elapsed / duration;
      
      if (progress < 1) {
        // 随机摇摆
        const shake = (Math.random() - 0.5) * intensity * 0.1;
        this.bobber.position.x = this.bobberPosition.x + shake;
        this.bobber.position.z = this.bobberPosition.z + shake;
        
        // 触觉反馈
        if (Math.random() < 0.3) {
          PicoVRConfig.triggerFishingHaptic(this.rightController, 'bite');
        }
        
        requestAnimationFrame(animate);
      } else {
        this.bobber.position.copy(this.bobberPosition);
      }
    };
    
    animate();
    
    // 通知水面系统创建鱼咬钩涟漪
    this.dispatchEvent('fishBite', {
      position: this.bobberPosition.clone(),
      intensity: intensity
    });
  }
  
  getRodTipPosition() {
    // 计算钓鱼竿顶端位置
    const tipPosition = new THREE.Vector3(0, 2, -1);
    
    if (this.isVRMode && this.rightController) {
      // VR模式下使用控制器位置
      tipPosition.copy(this.rightController.position);
      tipPosition.y += 0.2;
    }
    
    return tipPosition;
  }
  
  updateFishingLine() {
    // 更新钓鱼线形状
    const tipPosition = this.getRodTipPosition();
    const bobberPos = this.bobber.position;
    
    const linePoints = [];
    const segments = 20;
    
    for (let i = 0; i <= segments; i++) {
      const t = i / segments;
      
      // 计算悬链线（catenary curve）
      const x = THREE.MathUtils.lerp(tipPosition.x, bobberPos.x, t);
      const z = THREE.MathUtils.lerp(tipPosition.z, bobberPos.z, t);
      
      // 添加重力下垂效果
      const sag = Math.sin(t * Math.PI) * this.lineLength * 0.1;
      const y = THREE.MathUtils.lerp(tipPosition.y, bobberPos.y, t) - sag;
      
      linePoints.push(new THREE.Vector3(x, y, z));
    }
    
    this.fishingLine.geometry.setFromPoints(linePoints);
  }
  
  // 事件系统
  dispatchEvent(eventType, data) {
    const event = new CustomEvent(eventType, { detail: data });
    document.dispatchEvent(event);
  }
  
  // 在VR模式中更新钓鱼竿位置
  updateVRPosition() {
    this.isVRMode = this.renderer.xr.isPresenting;
    
    if (this.isVRMode && this.rightController) {
      // VR模式下钓鱼竿跟随右手控制器
      this.rodGroup.position.copy(this.rightController.position);
      this.rodGroup.rotation.copy(this.rightController.rotation);
    } else {
      // 非VR模式下固定位置
      this.rodGroup.position.set(0.5, 1.2, 0);
      this.rodGroup.rotation.set(-Math.PI / 6, Math.PI / 8, 0);
    }
  }
  
  // 更新方法
  update(deltaTime) {
    this.updateVRPosition();
    
    // 收竿逻辑
    if (this.isReeling) {
      this.lineLength = Math.max(this.lineLength - deltaTime * 5, this.minLineLength);
      
      // 更新浮漂位置（拉近）
      const direction = this.getRodTipPosition().sub(this.bobberPosition).normalize();
      this.bobberPosition.add(direction.multiplyScalar(deltaTime * 3));
      this.bobber.position.copy(this.bobberPosition);
    }
    
    // 浮漂浮动动画
    this.bobberFloating += deltaTime * 2;
    this.bobber.position.y = this.bobberPosition.y + Math.sin(this.bobberFloating) * 0.02;
    
    // 更新钓鱼线
    this.updateFishingLine();
  }
  
  // 销毁
  destroy() {
    if (this.rodGroup) {
      this.scene.remove(this.rodGroup);
    }
    
    if (this.bobber) {
      this.scene.remove(this.bobber);
    }
    
    if (this.rightController) {
      this.scene.remove(this.rightController);
    }
    
    if (this.leftController) {
      this.scene.remove(this.leftController);
    }
  }
}

export { FishingRod }; 